<?php

namespace app\admin\logic;

use think\facade\Db;
use app\data\util\HttpUtil;
use ba\Exception;
use think\facade\Cache;
use app\common\library\Excel;

class DashboardLogic
{
    protected $model = null;

    public function __construct()
    {
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $exchange = Cache::store('redis')->get('ba_exchange');
        if(empty($exchange)){
            $exchange = Db::name('exchange')
                ->order('date desc')
                ->find();
            Cache::store('redis')->set('ba_exchange', $exchange, 3600);
        }
        
        //今日时间戳
        $start_time = strtotime(date('Y-m-d 00:00:00', time()-16*3600));
        $end_time = strtotime(date('Y-m-d 23:59:59', time()-16*3600));
        //昨日时间戳
        $start_timey = $start_time - 24*3600;
        $end_timey = $end_time - 24*3600;

        //今日销售额
        $where = [];
        $where[]  = ['a.createtime', '>=', $start_time];
        $where[]  = ['a.createtime', '<=', $end_time];
        $TodaysSalesRevenue = $this->SalesRevenue($where);
        
        //昨日销售额
        $whereYesterday = [];
        $whereYesterday[]  = ['a.createtime', '>=', $start_timey];
        $whereYesterday[]  = ['a.createtime', '<=', $end_timey];
        $YesterdaysSalesRevenue = $this->SalesRevenue($whereYesterday);

        //今日退款

        $refund_subtotal = number_format((float)$TodaysSalesRevenue['total_amount'] * $exchange['refund_fee'] / 100, 2, '.', '');
        //昨天退款
        $Yesterday_refund_subtotal = number_format((float)$YesterdaysSalesRevenue['total_amount'] * $exchange['refund_fee'] / 100, 2, '.', '');

        //今日广告
        $whereAdvertisement = [];
        $whereAdvertisement[]  = ['a.stat_time', '>=', $start_time];
        $whereAdvertisement[]  = ['a.stat_time', '<=', $end_time];

        $Advertisement = $this->Advertisement($whereAdvertisement);

        //昨天广告
        $whereYesterdayAdvertisement = [];
        $whereYesterdayAdvertisement[]  = ['a.stat_time', '>=', $start_timey];
        $whereYesterdayAdvertisement[]  = ['a.stat_time', '<=', $end_timey];
        $YesterdayAdvertisement = $this->Advertisement($whereYesterdayAdvertisement);
        
        //时间搜索
        $day_change = $params['day_change'] ?? 0;
        switch ($day_change) {
            case '1':
                $start_time = strtotime(date('Y-m-d 00:00:00', time()-16*3600-24*3600));
                $end_time = strtotime(date('Y-m-d 23:59:59', time()-16*3600-24*3600));
                break;
            case '2':
                $start_time = strtotime(date('Y-m-d 00:00:00', time()-16*3600));
                $end_time = strtotime(date('Y-m-d 23:59:59', time()-16*3600));
                break;
            case '3':
                $start_time = strtotime(date('Y-m', time()));
                $end_time = strtotime(date('Y-m-d 00:00:00', strtotime('+1 month', $start_time)))-1;
                break;
            default:
                $start_time = strtotime(date('Y-m-d 00:00:00', time()-16*3600));
                $end_time = strtotime(date('Y-m-d 23:59:59', time()-16*3600));
        }

        $arr = Cache::store('redis')->get('DashboardList'.$start_time.''.$end_time);
        if(!empty($arr)){
            // return json(DefaultResponse(200, true, '获取缓存成功', $arr));
        }
        //统计店铺销售额-柱状图
        $whereStatisticalSalesRevenue = [];
        $whereStatisticalSalesRevenue[]  = ['a.createtime', '>=', $start_time];
        $whereStatisticalSalesRevenue[]  = ['a.createtime', '<=', $end_time];
        $StatisticalSalesRevenue = $this->StatisticalSalesRevenue($whereStatisticalSalesRevenue);

        //统计广告-柱状图
        $whereStatisticalAdvertising = []; 
        $whereStatisticalAdvertising[]  = ['a.stat_time', '>=', $start_time];
        $whereStatisticalAdvertising[]  = ['a.stat_time', '<=', $end_time];
        $StatisticalAdvertising = $this->StatisticalAdvertising($whereStatisticalAdvertising);
        
        //统计运营销售额-柱状图
        $whereSalesRevenue = [];
        $whereSalesRevenue[]  = ['stat_time_day', '>=', $start_time];
        $whereSalesRevenue[]  = ['stat_time_day', '<=', $end_time];
        $StatisticsOfOperationalSalesRevenue = $this->StatisticsOfOperationalSalesRevenue($whereSalesRevenue);
        
        $arr['TodaysSalesRevenue'] = $TodaysSalesRevenue;
        $arr['YesterdaysSalesRevenue'] = $YesterdaysSalesRevenue;
        $arr['Advertisement'] = $Advertisement;
        $arr['YesterdayAdvertisement'] = $YesterdayAdvertisement;
        $arr['StatisticalSalesRevenue'] = $StatisticalSalesRevenue;
        $arr['StatisticalAdvertising'] = $StatisticalAdvertising;
        $arr['StatisticsOfOperationalSalesRevenue'] = $StatisticsOfOperationalSalesRevenue;
        $arr['refund_subtotal'] = $refund_subtotal;
        $arr['Yesterday_refund_subtotal'] = $Yesterday_refund_subtotal;

        Cache::store('redis')->set('DashboardList'.$start_time.''.$end_time, $arr, 60);
        return json(DefaultResponse(200, true, '获取成功', $arr));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 销售额
     * @author zhangheng
     */
    public function SalesRevenue($where = [])
    {
        $SalesRevenue = Db::name('order')
            ->field('
                COUNT(a.id) as count,
                sum(total_amount) as total_amount,
                sum(shipping_fee_platform_discount) as shipping_fee_platform_discount,
                sum(platform_discount) as platform_discount,
                sum(tax) as tax
            ')
            ->alias('a')
            ->where($where)
            ->where('a.status','<>', 'CANCELLED')
            ->order('a.total_amount desc')
            ->find();

        //面板销售额
        $SalesRevenue['total_amount'] = number_format((float)$SalesRevenue['total_amount'] + $SalesRevenue['platform_discount'] + $SalesRevenue['shipping_fee_platform_discount'] - $SalesRevenue['tax'], 2, '.', '');
        $SalesRevenue['shipping_fee_platform_discount'] = getRes($SalesRevenue['shipping_fee_platform_discount']);
        $SalesRevenue['platform_discount']              = getRes($SalesRevenue['platform_discount']);
        $SalesRevenue['tax']                            = getRes($SalesRevenue['tax']);
        return $SalesRevenue;
    }
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 广告
     * @author zhangheng
     */
    public function Advertisement($where = [])
    {
        $advertising = Db::name('advertising_campaign')
            ->field('sum(a.spend) as spend,sum(a.total_onsite_shopping_value) as total_onsite_shopping_value')
            ->alias('a')
            ->join('ba_advaccount b', 'b.advertiser_id = a.advertiser_id', 'left')
            ->where($where)
            ->whereNotIn('b.id', function($query) {  
                $query->name('advaccount_admin')  
                    ->where('admin_id', '=', 37)  
                    ->field('advertiser_id');  
            })
            ->order('a.spend desc')
            ->find();
        if(!empty($advertising['total_onsite_shopping_value']) && !empty($advertising['spend'])){
            $advertising['total_onsite_shopping_value'] = number_format($advertising['total_onsite_shopping_value'], 2, '.', '');
            $advertising['onsite_shopping_roas'] = number_format($advertising['total_onsite_shopping_value'] / $advertising['spend'], 2, '.', '');
        }
        $advertising['spend'] = getRes($advertising['spend']);
        return $advertising;
    }
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 统计
     * @author zhangheng
     */
    public function StatisticalSalesRevenue($where = [])
    {
        $sales_form = Db::name('order')
            ->field('a.shop_id,sum(a.total_amount) as `value`,COUNT(a.id) as `count`, b.name as `key`')
            ->alias('a')
            ->join('ba_shops b', 'b.id = a.shop_id', 'left')
            ->where($where)
            ->where('a.status','<>', 'CANCELLED')
            ->group('a.shop_id')
            ->select()->toArray();
        $shop_ids = [];
        foreach ($sales_form as &$sale) {
            $shop_ids[] = $sale['shop_id'];
            $sale['value'] = number_format((float) $sale['value'], 2, '.', '');
            $sale['count'] = (int) $sale['count'];
        }
        $shop_ids = [12,1];
        if(!empty($shop_ids)){
            $shops = Db::name('shops')
                ->field('name')
                ->whereNotIn('id', $shop_ids)
                ->select()->toarray();
            foreach ($shops as $k=>$v) {
                $sales_form_arr['key'] = $v['name'];
                $sales_form_arr['value'] = 0;
                $sales_form_arr['count'] = 0;
                $sales_form[] = $sales_form_arr;
            }
        }
        return $sales_form;
    }
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 统计
     * @author zhangheng
     */
    public function StatisticalAdvertising($where = [])
    {
        $advertising_form = Db::name('advertising_campaign')
            ->field('SUM(a.total_onsite_shopping_value) as `income`, SUM(a.spend) as `value`, b.advertiser_name as `key`')
            ->alias('a')
            ->join('ba_advaccount b', 'b.advertiser_id = a.advertiser_id', 'left')
            ->where($where)
            ->where('a.spend', '>', 0)
            ->group("a.advertiser_id, b.advertiser_name")
            ->order('value desc')
            ->limit(10)
            ->select()->toArray();
        if(!empty($advertising_form)){
            $spend_column = array_column($advertising_form, 'value');
            array_multisort($spend_column, SORT_ASC, $advertising_form);
            foreach ($advertising_form as &$sale) {
                $sale['value'] = number_format((float) $sale['value'], 2, '.', '');
                $sale['income'] = number_format((float) $sale['income'], 2, '.', '');
            }
        }  
        return $advertising_form;
    }
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 统计
     * @author zhangheng
     */
    public function StatisticsOfOperationalSalesRevenue($where = [])
    {
        $list = Db::name('advertising_report')
            ->field('SUM(total_onsite_shopping_value) as `income`, SUM(spend) as `value`, name as `key`')
            ->where($where)
            ->group("name")
            ->select()->toarray();
        foreach ($list as &$sale) {
            $sale['value'] = number_format((float) $sale['value'], 2, '.', '');
            $sale['income'] = number_format((float) $sale['income'], 2, '.', '');
        }
        return $list;
    }
}
